<template>
  <div class="canvas">
    <header class="header">
      <div class="title">
        <img src="@/assets/images/01_11.png" alt class="img_zuo" @click="jumpReturn" />
        <div>{{ routers === '/signature_be_list' ? '被检查人签名' : '检查人签名' }}</div>
      </div>
    </header>
    <div class="canvas-box">
      <div id="canvas"></div>
      <div class="canvas-btn">
        <div class="canvas-btn-box">
          <div class="btns" id="clearCanvas">清除</div>
          <div class="btns" @click="jumpReturn">关闭</div>
          <div
            class="btns"
            :class="coordinatesX !== 0 && coordinatesY !== 0 ? '' : 'buttons'"
            :style="coordinatesX !== 0 && coordinatesY !== 0 ? '' : 'background-color: #8f8f94'"
            id="saveCanvas">确定</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import qs from 'qs';
import terminal from '@/assets/js/terminal';
import {Toast} from "vant";
export default {
  data () {
    return {
      routers: '',
      coordinatesX: 0,
      coordinatesY: 0,
      userId: 0,
      responseText: 0,
      repeat: 0,
      index: 0,
      type: 0
    };
  },
  mounted () {
    this.userId = Number(localStorage.getItem("userId"));
    this.routers = sessionStorage.getItem('signature');
    this.responseText = Number(localStorage.getItem("responseText"));
    this.type = this.$route.query.id;
    this.canvas();
  },
  methods: {
    //  返回签名列表
    jumpReturn () {
      this.$router.back();
    },
    //  保存
    upload (url) {
      let data = {
        userId: this.userId,
        noweInfoId: this.responseText,
        imgUrl: url,
        type: this.type
      };
      this.axios.post(`${this.$global_msg.Url.host}/partroInspection/saveGenerySignature`,
      qs.stringify(data)).then(res => {
        if (res.data.code === 200) {
          this.repeat = 1;
          let a = this.routers;
          this.$toast({
            message: '上传签名成功！',
            onClose: _ => {
              this.$router.back();
            }
          })
        } else {
          Toast(res.data.msg || '保存签名失败！')
        }
      }).catch( e => terminal._error(e));
    },
    //  canvas获取
    canvas () {
      let a = {
        el: document.querySelector('#canvas'),
        clearEl: document.querySelector('#clearCanvas'),
        saveEl: document.querySelector('#saveCanvas')
      }
      this.lineCanvas(a);
    },
    //  画布操作
    lineCanvas (obj) {
      this.lineWidth = 2;
      this.color = '#000';
      this.background = '#fff';
      for (const index in obj) {
        this[index] = obj[index];
      }
      this.canvas = document.createElement('canvas');
      if (!(this.canvas.getContext && this.canvas.getContext('2d'))) {
        this.section = document.createElement('section');
        this.section.className = 'errorCanvas';
        this.section.innerHTML = '对不起，当前浏览器暂不支持此功能！';
        this.el.prepend(this.section);
        return;
      }
      this.canvas.width = this.el.clientWidth;
      this.canvas.height = this.el.clientHeight;
      this.el.prepend(this.canvas);
      this.setup();
      console.log(this.cxt)
      // 开始绘制
      this.canvas.addEventListener('touchstart', function (e) {
        this.cxt.beginPath();
        this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY - 80);
      }.bind(this), false);
      // 绘制中
      this.canvas.addEventListener('touchmove', function (e) {
        this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY - 80);
        this.coordinatesX = e.changedTouches[0].pageX
        this.coordinatesY = e.changedTouches[0].pageY
        this.cxt.stroke();
      }.bind(this), false);
      // 结束绘制
      this.canvas.addEventListener('touchend', function () {
        this.cxt.closePath();
      }.bind(this), false);
      // 清除画布
      this.clearEl.addEventListener('click', function () {
        this.setup();
        this.coordinatesX = 0
        this.coordinatesY = 0
      }.bind(this), false);
      // 保存图片
      this.saveEl.addEventListener('click', function () {
        this.index++
        if (this.index <= 1) {
          const imgPng = this.compressionSize(this.canvas.toDataURL('image/png'), 'image/png');
          const imgJpg = this.compressionSize(this.canvas.toDataURL('image/jpeg'), 'image/jpeg');
          if (imgPng !== undefined) {
            this.upload(imgJpg);
          } else {
            this.upload(imgPng);
          }
        }
      }.bind(this), false);
    },
    //  压缩大小
    compressionSize (data, type) {
      let size = 0;
      const equalIndex = data.indexOf('=');  // 获取=号下标
      if (equalIndex > 0) {
        const str = data.substring(0, equalIndex); // 去除=号
        const strLength = str.length;
        const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
        size = (Math.floor(fileLength)/1024/1024).toFixed(2);
      } else {
        const strLength = data.length;
        const fileLength = strLength - (strLength / 8) * 2;
        size = (Math.floor(fileLength)/1024/1024).toFixed(2);
      }
      if(size < 1){
        return this.canvas.toDataURL(type, 1);
      }else if(size > 1 && size < 2){
        return this.canvas.toDataURL(type, 0.5);
      }else{
        return this.canvas.toDataURL(type, 0.2);
      }
    },
    //  设置
    setup () {
      this.cxt = this.canvas.getContext('2d');
      this.cxt.fillStyle = this.background;
      this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height);
      this.cxt.strokeStyle = this.color;
      this.cxt.lineWidth = this.lineWidth;
      this.cxt.lineCap = 'round'; // 线条末端添加圆形线帽，减少线条的生硬感
      this.cxt.lineJoin = 'round'; // 线条交汇时为原型边角
      // 利用阴影，消除锯齿
      this.cxt.shadowBlur = 1;
      this.cxt.shadowColor = '#000';
    }
  }
}
</script>

<style scoped>
  .canvas-box {
    background-color: #f7f7f9;
    padding: 30px 20px 0;
    margin-top: 1.8519rem;
  }
  .header {
    height: 1.8519rem;
    background: #007aff;
    padding-top: 0.8333rem;
    box-sizing: border-box;
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 20;
    font-size: 0.388888rem;
  }

  .title {
    padding: 0 0.3704rem;
    display: flex;
    align-items: center;
    color: #fff;
  }

  .title > div {
    width: 100%;
    font-size: 0.4444rem;
    text-align: center;
  }
  .img_zuo {
    width: 0.2593rem;
    height: 0.463rem;
  }
  /*画布*/
  #canvas {
    position: relative;
    width: 100%;
    height: calc(100vh - 4.85rem);
    border-radius: 20px;
    overflow: hidden;
  }
  #canvas canvas {
    display: block;
  }
  #saveCanvas {
    right: 0;
  }
  /*按钮*/
  .canvas-btn {
    height: 2.7rem;
  }
  .canvas-btn-box {
    background-color: #f7f7f9;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  .btns {
    background-color: #2b6cfe;
    width: 250px;
    line-height: 80px;
    text-align: center;
    color: #fff;
    padding: 16px 0;
    border-radius: 10px;
    transform: rotate(90deg);
  }
  .buttons {
    pointer-events: none;
  }
</style>
